package gw.com.android.ui.chart;

import android.os.Bundle;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.chart.components.LimitLine;
import com.gwtsz.chart.output.customer.MyLineChart;
import com.gwtsz.chart.output.customer.MyXAxis;
import com.gwtsz.chart.output.customer.MyYAxis;
import com.gwtsz.chart.output.utils.ChartThemeUtil;
import com.gwtsz.chart.output.utils.GTTKDataManager;
import com.gwtsz.chart.output.utils.GTTNotifyModel;
import com.gwtsz.chart.output.utils.GTTTimeDataModel;
import com.gwtsz.gts2.hx.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.chart.manager.ChartTimeViewImp;
import gw.com.android.ui.chart.manager.ChartTimeViewInterface;
import gw.com.android.ui.quote2.widget.OnQuoteChartProgressStatusChangeListener;
import gw.com.android.utils.ServerConnnectUtil;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.ProductPrecision;

/**
 * Created by reeta.zou on 2016/10/13.
 * 分时图界面
 */
public class ChartTimeFragment extends PushMsgTabFragment {

    @BindView(R.id.time_chart)
    MyLineChart mMyLineChart;
    /**
     * 数据转换&控制
     */
    ChartTimeViewInterface mChartTimeView;

    private int mUiCode;//产品code
    private int zoneType;
    private DataItemDetail mProItem;
    public boolean isLoading = false;

    private static String TAG = ChartTimeFragment.class.getSimpleName();
    private static String METHOD = "class=" + TAG + " method=";
    private int decimalNum = 0;
    private OnQuoteChartProgressStatusChangeListener onStatusChangeListener;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_chart_time;
    }

    @Override
    public void setArguments(Bundle args) {
        super.setArguments(args);
        mUiCode = getArguments().getInt("uiCode", 0);
        zoneType = getArguments().getInt("zoneType", GTSConst.ZONE_TYPE_SELF);
    }

    @Override
    protected void initLayoutView() {
        ButterKnife.bind(this, mRootView);
    }

    @Override
    protected void initViewData() {
        if (mChartTimeView == null) {
            /* 绑定控件到控制层 */
            mChartTimeView = new ChartTimeViewImp(mMyLineChart, getActivity());
        }
        /* 传输数据到控制层 */
        mChartTimeView.setTimeDataList(GTTKDataManager.instance().mTimeDataList);
        mProItem = DataManager.instance().getTickModel(mUiCode);
        if (null != mProItem) {
            mChartTimeView.setProductPrecision(new ProductPrecision(0, mProItem.getInt(GTSConst.JSON_KEY_DIGITS)));
            decimalNum = mProItem.getInt(GTSConst.JSON_KEY_DIGITS);
            mChartTimeView.initPrices(mProItem.getString(GTSConst.JSON_KEY_CURPRICE),
                    mProItem.getString(GTSConst.JSON_KEY_CLOSEPRICE),
                    mProItem.getString(GTSConst.JSON_KEY_HIGHPRICE),
                    mProItem.getString(GTSConst.JSON_KEY_LOWPRICE));
        }
        if (GTTKDataManager.instance().hasTimeData()) {
            setStartTime(GTTKDataManager.instance().uiStartTime);
            onRefreshData(mUiCode);
        } else {
            reqData();
        }

        if (onStatusChangeListener != null) {
            onNightMode(onStatusChangeListener.isNight());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",hidden=" + hidden);
        super.onHiddenChanged(hidden);
        cleanHighLight();
        if (!hidden) {
            reqData();
        }
    }

    @Override
    public void registerRxBus() {
        Disposable timeListRegister = RxBus.getInstance().register(GTSConst.REPLY_UPTRENDDATA_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        Logger.e("onServerResponse timeListRegister 收到分时回包！" + (null == bundle));
                        if (null == bundle) {
                            return;
                        }

                        ArrayList<GTTTimeDataModel> mTimeList = (ArrayList<GTTTimeDataModel>) bundle.getSerializable("mTimeList");
                        if (null != mTimeList && mTimeList.size() > 0) {
                            GTTKDataManager.instance().addTimeList(mTimeList);
                        }
                        GTTNotifyModel obj = (GTTNotifyModel) bundle.getSerializable("GTTNotifyModel");
                        if (bundle.getInt("iValue") != 0) {
                            if (obj.nShNum == 0 && bundle.getInt("iValue") == 1064) {
                                noDataView(bundle.getInt("iValue"));
                            } else if (bundle.getInt("iValue") == 1063) {
                                // 请求分时数据超时
                                noDataView(bundle.getInt("iValue"));
                            } else {
                                onFailDeal(bundle.getInt("iValue"));
                            }
                        } else if (null != obj && obj.uiCodeID == mUiCode) {
                            GTTKDataManager.instance().uiStartTime = obj.uiStartTime;
                            setStartTime(GTTKDataManager.instance().uiStartTime);
                            onRefreshData(bundle.getInt("iNotification"));
                        } else {
                            onProgressVisible(false);
                        }

                    }
                });

        bindSubscription(timeListRegister);

        Disposable timeTickRegister = RxBus.getInstance().register(GTSConst.REPLY_UPTRENDTICK_UPDATE + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        if (null != bundle && bundle.getInt("iNotification") == mUiCode) {
                            DataItemDetail tickModel = DataManager.instance().getTickModel(bundle.getInt("iNotification"));
                            GTTTimeDataModel mRound = (GTTTimeDataModel) bundle.getSerializable("object");
                            if (null != tickModel) {
                                if (isResumed() && isVisible()) {
                                    onRefreshPrice(tickModel, mRound);
                                }
                            }
                        }
                    }
                });

        bindSubscription(timeTickRegister);

        Disposable nextTimeRegister = RxBus.getInstance().register(GTSConst.REPLY_UPTRENDDATA_NEXTDAY + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {

                    }
                });

        bindSubscription(nextTimeRegister);
    }

    /**
     * 请求数据
     */
    public void reqData() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        if (!isHidden() && NetworkMonitor.hasNetWork() && !ServerConnnectUtil.instance().hasReConnectQuote()) {
            if (isLoading) {
                return;
            }

            onProgressVisible(true);
            isLoading = true;
            AppTerminal.instance().requestTimeData(zoneType, mUiCode, GTTKDataManager.instance().lastTime, -1, 0);
        }
    }

    /**
     * 设置起始时间
     */
    public void setStartTime(int uiStartTime) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",uiStartTime=" + uiStartTime);
        int startTime = 0;
        if (mProItem.getInt(GTSConst.JSON_KEY_STARTTIME) > 0) {
            startTime = uiStartTime - 24 * 60 * 60 + mProItem.getInt(GTSConst.JSON_KEY_STARTTIME) * 60;
        } else {
            startTime = uiStartTime;
        }
        //mTimeView.setStartTime(startTime);
        /* new chart */
        mChartTimeView.setStartTime(startTime);
    }

    /**
     * 刷新数据
     */
    public void onRefreshData(int code) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",code=" + code);
        isLoading = false;
        onProgressVisible(false);
        if (null != mChartTimeView && code == mUiCode && GTTKDataManager.instance().mTimeDataList.size() > 0) {
            /* new chart*/
            mChartTimeView.initPrices(mProItem.getString(GTSConst.JSON_KEY_CURPRICE),
                    mProItem.getString(GTSConst.JSON_KEY_CLOSEPRICE),
                    mProItem.getString(GTSConst.JSON_KEY_HIGHPRICE),
                    mProItem.getString(GTSConst.JSON_KEY_LOWPRICE));

            mChartTimeView.refreshData(mUiCode);
            mChartTimeView.setTimeDataList(GTTKDataManager.instance().mTimeDataList);
            mChartTimeView.invalidate();
        }
    }

    /**
     * 失败处理
     */
    public void onFailDeal(int failCode) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",failCode=" + failCode);
        isLoading = false;
        onProgressVisible(false);
        String error = ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012);
        if (!ConfigType.SERVER_ERROR_1064.equals(failCode + "")) {
            showToastPopWindow(error);
        }
    }

    /**
     * 刷新报价,有新的报价时，更新界面数据
     */
    public void onRefreshPrice(DataItemDetail model, GTTTimeDataModel mRound) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",model=" + model + ",mRound=" + mRound);
        if (isLoading || (null != mChartTimeView && !mChartTimeView.hasData())) {
            return;
        }
        if (null != model) {
            mProItem = model;
            if (null != mChartTimeView) {
//                Logger.e("timeview onRefreshPrice");
                ReqDataUtils.instance().updateLastTimeLine(mRound);
                /* new chart */
                mChartTimeView.initPrices(mProItem.getString(GTSConst.JSON_KEY_CURPRICE),
                        mProItem.getString(GTSConst.JSON_KEY_CLOSEPRICE),
                        mProItem.getString(GTSConst.JSON_KEY_HIGHPRICE),
                        mProItem.getString(GTSConst.JSON_KEY_LOWPRICE));
                /* 载入数据 */
                mChartTimeView.setTimeDataList(GTTKDataManager.instance().mTimeDataList);
                /* 刷新 */
                mChartTimeView.invalidate();
            }
        }
    }

    /**
     * 显示隐藏加载圈
     */
    public void onProgressVisible(boolean isVisible) {
        if (onStatusChangeListener != null) {
            onStatusChangeListener.onProgressVisible(isVisible);
        }
    }

    public void setProductDecimalNum(int num) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",num=" + num);
        if (num != decimalNum && null != mChartTimeView) {
            mChartTimeView.setProductPrecision(new ProductPrecision(0, num));
            decimalNum = num;
            mChartTimeView.refreshDecimalNum(num);
            cleanHighLight();
        }
    }

    /**
     * 清除光标
     **/
    private void cleanHighLight() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        mMyLineChart.highlightValue(null);
    }

    /**
     * 无数据情况图表显示
     **/
    public void noDataView(int failCode) {
        mMyLineChart.noDataView();
        isLoading = false;
        onProgressVisible(false);
        onFailDeal(failCode);
    }

    public void onNightMode(boolean isNight) {
        MyXAxis xAxis = mMyLineChart.getXAxis();
        MyYAxis axisLeft = mMyLineChart.getAxisLeft();
        MyYAxis axisRight = mMyLineChart.getAxisRight();
        if (isNight) {
            mMyLineChart.setBackgroundColor(getResources().getColor(R.color.color_night_bg_d2));
            mMyLineChart.setBorderColor(getResources().getColor(R.color.color_night_line));
            if (xAxis != null) {
                xAxis.setTextColor(getResources().getColor(R.color.color_7F848F));
                xAxis.setGridColor(getResources().getColor(R.color.color_night_line));
                xAxis.setAxisLineColor(getResources().getColor(R.color.color_night_line));
            }
            if (axisLeft != null) {
                axisLeft.setGridColor(getResources().getColor(R.color.color_night_line));
            }
            if (axisRight != null) {
                axisRight.setGridColor(getResources().getColor(R.color.color_night_line));
                axisRight.setLimitLineColor(getResources().getColor(R.color.color_night_line));
                List<LimitLine> lines = axisRight.getLimitLines();
                if (lines != null) {
                    for (LimitLine line : lines) {
                        line.setLineColor(getResources().getColor(R.color.color_night_line));
                    }
                }
            }
            mMyLineChart.getRendererLeftYAxis().setNeutralColor(getResources().getColor(R.color.color_7F848F));
            mMyLineChart.getRendererLeftYAxis().setDecreasingColor(getResources().getColor(R.color.color_7F848F));
            mMyLineChart.getRendererLeftYAxis().setIncreasingColor(getResources().getColor(R.color.color_7F848F));
            mMyLineChart.getRendererRightYAxis().setNeutralColor(getResources().getColor(R.color.color_7F848F));
            mMyLineChart.getRendererRightYAxis().setDecreasingColor(getResources().getColor(R.color.color_7F848F));
            mMyLineChart.getRendererRightYAxis().setIncreasingColor(getResources().getColor(R.color.color_7F848F));
            mMyLineChart.postInvalidate();
        } else {
            mMyLineChart.setBackgroundColor(getResources().getColor(R.color.color_f));
            mMyLineChart.setBorderColor(getResources().getColor(R.color.color_text));
            if (xAxis != null) {
                xAxis.setTextColor(getResources().getColor(R.color.color_888888));
                xAxis.setGridColor(getResources().getColor(R.color.color_line));
                xAxis.setAxisLineColor(getResources().getColor(R.color.color_line));
            }
            if (axisLeft != null) {
                axisLeft.setGridColor(getResources().getColor(R.color.color_line));
            }
            if (axisRight != null) {
                axisRight.setGridColor(getResources().getColor(R.color.color_line));
                axisRight.setLimitLineColor(0);
                List<LimitLine> lines = axisRight.getLimitLines();
                if (lines != null) {
                    for (LimitLine line : lines) {
                        line.setLineColor(getResources().getColor(R.color.color_line));
                    }
                }
            }
            mMyLineChart.getRendererLeftYAxis().setNeutralColor(ChartThemeUtil.instance().IdleColor);
            mMyLineChart.getRendererLeftYAxis().setDecreasingColor(ChartThemeUtil.instance().FallColor);
            mMyLineChart.getRendererLeftYAxis().setIncreasingColor(ChartThemeUtil.instance().RiseColor);
            mMyLineChart.getRendererRightYAxis().setNeutralColor(ChartThemeUtil.instance().IdleColor);
            mMyLineChart.getRendererRightYAxis().setDecreasingColor(ChartThemeUtil.instance().FallColor);
            mMyLineChart.getRendererRightYAxis().setIncreasingColor(ChartThemeUtil.instance().RiseColor);
            mMyLineChart.postInvalidate();
        }
    }

    public void setOnStatusChangeListener(OnQuoteChartProgressStatusChangeListener onStatusChangeListener) {
        this.onStatusChangeListener = onStatusChangeListener;
    }

    public void setUiCodeAndZoneType(int uiCode, int zoneType) {
        this.mUiCode = uiCode;
        this.zoneType = zoneType;
        GTTKDataManager.instance().clearTimeData();
        initViewData();
    }
}
